<?php

error_reporting(E_ALL);
require_once('model/forecast.class.php');

class xmlParser {


	public function getWeather($url){
		$arr = explode('/', $url);
		
		
		$tmpFile =  'storage/files/'.$arr[4].$arr[5].$arr[6].$arr[7].'.xml';
		$objFile = 'storage/objects/'.$arr[4].$arr[5].$arr[6].$arr[7].'.obj';
		if (file_exists($tmpFile) && (time() - filemtime($tmpFile)) < 300){
			$fh = fopen($objFile, 'r');
			$contents = '';
			while (!feof($fh)) {
				$contents .= fread($fh, 8192);
			}
			fclose($fh);
			$arr = unserialize($contents);
			return $arr;
		} else {
			
			$this->readFile(utf8_decode($url), utf8_decode($tmpFile));
				
			$arr = $this->parseFile(utf8_encode($tmpFile));

			$str = serialize($arr);
			$fh = fopen(utf8_decode($objFile), 'w');
			
			fwrite($fh, $str);
			fclose($fh);
			
			return $arr;
		}
	}

	private function readFile($from, $to){

		$ch = curl_init($from);
		$fp = fopen($to, 'w');
		curl_setopt($ch, CURLOPT_FILE, $fp);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_exec($ch);
		curl_close($ch);
		fclose($fp);


	}

	private  function parseFile($url){
		
		$doc = new DOMDocument('1.0');
		
		
		$doc->load(utf8_decode(utf8_decode($url)));

		$xpath = new DOMXPath($doc);

		$query = '/weatherdata/forecast/tabular/time';
		$result = $xpath->query($query);

		$forecast = array(); // 3 times pr day,
		//echo $result->length;
		for ($i=0; $i<$result->length; $i++){
			$time = $result->item($i);
			$from = $time->getAttribute('from');
			$date = array_shift(explode('T', $from));
			$period = $time->getAttribute('period');
			$key = $date.'-'.$period;
			if ($period != 0){
				$obj = new forecastModel();
				$obj->setWindDir(   $time->getElementsByTagName('windDirection')->item(0)->getAttribute('deg'));
				$obj->setWindDirTxt($time->getElementsByTagName('windDirection')->item(0)->getAttribute('name'));
				$obj->setWindSpeed( $time->getElementsByTagName('windSpeed')->item(0)->getAttribute('mps'));
				$obj->setWindSpeedTxt($time->getElementsByTagName('windSpeed')->item(0)->getAttribute('name'));
				$obj->setTemperature($time->getElementsByTagName('temperature')->item(0)->getAttribute('value'));
				$obj->setPrecipitation($time->getElementsByTagName('precipitation')->item(0)->getAttribute('value'));
				$obj->setWeatherSymbol($time->getElementsByTagName('symbol')->item(0)->getAttribute('number'));
				$obj->setWeatherSymbolTxt($time->getElementsByTagName('symbol')->item(0)->getAttribute('name'));
				$forecast[$key] = $obj;
			}
		}
		return $forecast;
	}
}



// main()
//$uri = 'http://www.yr.no/sted/Norge/Telemark/Sauherad/Gvarv/varsel.xml';
//$obj = new xmlParser();
//$arr = $obj->getWeather($uri);
